/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;

namespace MyPhotoIndex.Utilities
{
    public sealed class WebUtilities
    {
        public static void DownloadFile(string url, string filePath, ProgressEventDelegate progress)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            int streamLength = (int)response.ContentLength;

            using (Stream responseStream = response.GetResponseStream())
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                int chunkSize = 4096;
                byte[] buffer = new byte[chunkSize];
                int bytesRead = 0;
                int totalBytes = 0;

                while ((bytesRead = responseStream.Read(buffer, 0, chunkSize)) > 0)
                {
                    fs.Write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;

                    if (progress != null)
                    {
                        bool stop = progress.Invoke(streamLength, totalBytes);
                        if (stop == true)
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
}
